﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
namespace WinnerCMS.PlugIn.FileWatcher
{
    /// <summary>
    /// 木马特征
    /// </summary>
    public class Token
    {
        /// <summary>
        /// 匹配多少就算确认
        /// </summary>
        public int Match = 1;

        public List<DNA> DNAs;

        /// <summary>
        /// 格式
        /// </summary>
        public string Format;

        public Token(XmlNode xn)
        {
            DNAs = new List<DNA>();

            if (xn.Attributes["Match"] != null)
            {
                int.TryParse(xn.Attributes["Match"].Value, out this.Match);
            }
            if (xn.Attributes["Format"] != null)
            {
                this.Format = xn.Attributes["Format"].Value;
            }
            foreach (XmlNode x in xn.ChildNodes)
            {
                DNA dna = new DNA();
                dna.Code = x.InnerText;
                dna.Regex = (x.Attributes.Count > 0 ? bool.Parse(x.Attributes["Regex"].Value) : false);

                DNAs.Add(dna);
            }
        }

        #region 确认是否匹配
        /// <summary>
        /// 确认是否匹配
        /// </summary>
        /// <returns></returns>
        public bool Confirm(string Content)
        {
            if (string.IsNullOrEmpty(Content) == true)
            {
                return false;
            }
            int i = 0;// 匹配数量
            foreach (DNA dna in DNAs)
            {
                if (dna.Regex == false)
                {
                    if (Content.Contains(dna.Code) == true)
                    {
                        i++;

                        if (this.Match == i)
                        {
                            return true;
                        }
                    }
                }
                else
                {
                    if (Regex.Match(Content, dna.Code).Success == true)
                    {
                        i++;

                        if (Match == i)
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        #endregion

    }
}